import { Button, Form, Input } from 'antd-mobile'
import {
  UserOutline,
  LockOutline,
  EyeInvisibleOutline,
  EyeOutline
} from 'antd-mobile-icons'
import { Link, useNavigate } from 'react-router-dom'
import { useState } from 'react'
import { loginApi } from '../../../api/user'

// 账号 + 密码登录
function Account() {
  const [visible, setVisible] = useState(false)
  const nav = useNavigate()

  // 表单的提交处理函数
  const onFormFinish = async (value) => {
    // 形参中的 value 就是表单校验通过后，需要提交给后端 API 接口的数据
    const result = await loginApi(value)
    console.log(result)
    localStorage.setItem('token', result.data.token)
    nav('/')
  }

  return (
    <div>
      <Form
        onFinish={onFormFinish}
        layout="horizontal"
        mode="card"
        requiredMarkStyle="none"
        style={{ '--prefix-width': 30 }}
        footer={
          <>
            <Button
              color="primary"
              block
              type="submit"
            >
              登录
            </Button>
            <div style={{ textAlign: 'right', marginTop: 15 }}>
              <Link to="/reg">去注册</Link>
            </div>
          </>
        }
      >
        {/* 在表单组件中，name 是加给 Form.Item 的，而不是 Input */}
        <Form.Item
          label={<UserOutline />}
          name="username"
          rules={[
            { required: true, message: '请填写账号！' },
            { min: 2, max: 15, message: '账号长度为2-15个字符！' }
          ]}
        >
          <Input placeholder="请输入账号" />
        </Form.Item>
        <Form.Item
          label={<LockOutline />}
          name="password"
          rules={[
            { required: true, message: '请填写密码！' },
            { min: 6, max: 15, message: '密码长度为6-15个字符！' }
          ]}
          extra={
            <div>
              {!visible ? (
                <EyeInvisibleOutline onClick={() => setVisible(true)} />
              ) : (
                <EyeOutline onClick={() => setVisible(false)} />
              )}
            </div>
          }
        >
          <Input
            placeholder="请输入密码"
            type={visible ? 'input' : 'password'}
          />
        </Form.Item>
      </Form>
    </div>
  )
}

export default Account
